export var MyCalendarTwo = function () {
  this.tree = new SegmentTree()
}

/**
 * @param {number} start
 * @param {number} end
 * @return {boolean}
 */
MyCalendarTwo.prototype.book = function (start, end) {
  const val = this.tree.query(start, end - 1)
  if (val < 2) {
    this.tree.update(start, end - 1, 1)
    return true
  }
  return false
}

/**
 * Your MyCalendarTwo object will be instantiated and called as such:
 * var obj = new MyCalendarTwo()
 * var param_1 = obj.book(start,end)
 */

/**
 * 线段树节点
 */
const Node = function (start, end, left, right) {
  this.val = 0
  this.left = left
  this.right = right
  this.start = start
  this.end = end
  this.lazy = 0
}

class SegmentTree {
  constructor() {
    this.root = new Node(0, 10 ** 9, null, null)
  }

  update(start, end, v, node = null) {
    if (end < start) return
    if (node === null) node = this.root
    const [nStart, nEnd] = [node.start, node.end]
    if (start <= nStart && nEnd <= end) {
      node.val += v
      node.lazy += v
      return
    }
    this.pushdown(node)
    const mid = (nStart + nEnd) >> 1
    if (start <= mid) this.update(start, end, v, node.left)
    if (end > mid) this.update(start, end, v, node.right)
    this.pushup(node)
  }

  pushdown(node) {
    const [nStart, nEnd] = [node.start, node.end]
    const mid = (nStart + nEnd) >> 1
    if (node.left === null) node.left = new Node(nStart, mid, null, null)
    if (node.right === null) node.right = new Node(mid + 1, nEnd, null, null)
    if (node.lazy) {
      node.left.val += node.lazy
      node.right.val += node.lazy
      node.left.lazy += node.lazy
      node.right.lazy += node.lazy
      node.lazy = 0
    }
  }
  pushup(node) {
    node.val = Math.max(node.left.val, node.right.val)
  }

  query(start, end, node = null) {
    if (end < start) return 0
    if (node === null) node = this.root
    const [nStart, nEnd] = [node.start, node.end]
    if (start <= nStart && nEnd <= end) return node.val
    this.pushdown(node)
    const mid = (nStart + nEnd) >> 1
    let ans = 0
    if (start <= mid) ans = this.query(start, end, node.left)
    if (end > mid) ans = Math.max(ans, this.query(start, end, node.right))
    return ans
  }
}
